package com.dragon.gencode.project.server;

import com.dragon.gencode.project.domain.GenTable;
import com.dragon.gencode.project.domain.GenTableColumn;
import com.dragon.gencode.util.BeanUtils;
import com.dragon.gencode.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName GenServer
 * @Description TODO
 * @Author dragon
 * @Date 2020-06-18 15:32
 * @Version 1.0
 **/
@Service("genServer")
public class GenServer {

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 获取数据库表
     * @return
     */
    public List<GenTable> getTables() {
        StringBuilder sb = new StringBuilder();
        sb.append("select  table_name, table_comment, create_time, update_time from information_schema.tables where table_schema = (select database());");
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString());
        List<GenTable> tables = BeanUtils.toBeanList(list, GenTable.class,k -> StringUtils.toCamelCase(k),null);
        return tables;
    }

    public List<GenTableColumn> getColumns(String table) {

        StringBuilder sb = new StringBuilder();

        sb.append(" SELECT ");
        sb.append(" 	column_name, ");
        sb.append(" 	( CASE WHEN ( is_nullable = 'no'  &&  column_key != 'PRI' ) THEN '1' ELSE '0' END ) AS is_required, ");
        sb.append(" 	( CASE WHEN column_key = 'PRI' THEN '1' ELSE '0' END ) AS is_pk, ");
        sb.append(" 	ordinal_position AS sort, ");
        sb.append(" 	column_comment, ");
        sb.append(" 	( CASE WHEN extra = 'auto_increment' THEN '1' ELSE '0' END ) AS is_increment, ");
        sb.append(" 	column_type  ");
        sb.append(" FROM ");
        sb.append(" 	information_schema.COLUMNS  ");
        sb.append(" WHERE ");
        sb.append(" 	table_schema = (SELECT DATABASE())  ");
        sb.append(" 	AND table_name = ?  ");
        sb.append(" ORDER BY ");
        sb.append(" 	ordinal_position ");
        if (StringUtils.isEmpty(table)) {
            throw new RuntimeException("table is empty");
        }
        String params[] = new String[]{table};
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sb.toString(), params);

        List<GenTableColumn> list = BeanUtils.toBeanList(maps, GenTableColumn.class, k -> StringUtils.toCamelCase(k),null);
        return list;
    }


}
